package com.aipsi.cws.supplier.exception;


import com.aipsi.cws.common.exception.CustomException;
import com.aipsi.cws.common.exception.CustomExceptionType;
import com.aipsi.cws.common.result.AjaxResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;


@ControllerAdvice
@Slf4j
public class WebExceptionHandler {

    @ResponseStatus()
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public AjaxResponse customerException(CustomException e) {
        log.error("错误类型为CustomException : "+e.getMessage());
        return AjaxResponse.error(e);
    }

    @ResponseStatus()
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public AjaxResponse duplicateKeyException(Exception e) {
        String[] split = e.getCause().getMessage().split("\'");
        StringBuilder errBuilder=new StringBuilder();
        String err = errBuilder.append("字段: " + split[1] + " 发生了" + (split[3].equals("PRIMARY") ? "主键重复" : "唯一键重复") + "的错误").toString();
        log.error("错误类型为duplicateKeyException : {}",err);
        return AjaxResponse.error(CustomExceptionType.INTERNAL_SERVER_ERROR,err);
    }

    @ResponseStatus()
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AjaxResponse exception(Exception e) {
        log.error("错误类型为Exception : "+e.getMessage());
        return AjaxResponse.error(CustomExceptionType.INTERNAL_SERVER_ERROR,e.getMessage());
    }


    @ResponseStatus()
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public AjaxResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("错误信息: ");
        fieldErrors.forEach(fieldError -> {
            stringBuilder.append(fieldError.getField()+"-->").append(fieldError.getDefaultMessage())
                    .append(",");
        });
        String err = stringBuilder.toString();
        log.error("错误类型为MethodArgumentNotValidException : "+err);
        return AjaxResponse.error(CustomExceptionType.ILLEGAL_ARGUMENT,err);
    }
}
